/*
 * Copyright (C) 2008 Matt Falkoski
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.falko.android.raven.animator;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AnimationQueue {

	private int maxQueueSize_ = 0;
	private LinkedList<Animation> queue_ = null;

	private final Lock lock_ = new ReentrantLock();
	private final Condition empty_ = lock_.newCondition();
	private final Condition full_ = lock_.newCondition();

	public AnimationQueue(int size) {
		maxQueueSize_ = size;
		queue_ = new LinkedList<Animation>();
	}

	public Animation take() {
		Animation front = null;
		lock_.lock();
		try {
			while (queue_.isEmpty()) {
				empty_.await();
			}
			front = queue_.removeFirst();
		} catch (InterruptedException e) {
			// log here
		} finally {
			full_.signalAll();
			lock_.unlock();
		}
		return front;
	}

	public void putAnimation(Animation a) {

		lock_.lock();
		try {
			while (queue_.size() == maxQueueSize_) {
				full_.await();
			}
			queue_.addLast(a);
		} catch (InterruptedException e) {
			// log here
		} finally {
			empty_.signalAll();
			lock_.unlock();
		}
	}

	public int size() {
		int size = 0;
		lock_.lock();
		size = queue_.size();
		lock_.unlock();
		return size;
	}

	public boolean isFull() {
		boolean full = false;
		lock_.lock();
		full = maxQueueSize_ == queue_.size();
		lock_.unlock();
		return full;

	}

}
